package com.apestech.api.condition.conlib;

import com.apestech.api.condition.ConditionTableQrySql;
import com.apestech.api.tables.SequenceManage;
import com.apestech.api.tables.modul.SeqField;
import com.apestech.formwork.condition.ConditionUtil;
import com.apestech.framework.db.SqlResultSet;
import com.apestech.framework.db.SqlSession;
import com.apestech.framework.db.callback.QueryCallBackHandler;
import com.apestech.framework.json.JSON;
import com.apestech.framework.json.JSONArray;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.util.DBPub;
import com.apestech.framework.xml.condition.modul.Condition;

import java.util.ArrayList;
import java.util.Map;

public class ConStop extends ConPub{
    private Condition condition;
    private SqlSession session;

    public ConStop(Condition condition) throws Exception {
        super(condition);
        this.condition=condition;
        session=condition.getSession();
    }

    public String stopSave(String mid, JSONObject json) throws Exception {
        String tabName=condition.getTableKey().getTabName(mid);
        String stopTab=tabName+"_EXEC_STOP";
        ConditionTableQrySql sql=new ConditionTableQrySql(tabName, session);
        if(!session.tableExists(stopTab)){
            session.getForDDL().createStopTableFromTable(tabName+"_EXEC", stopTab);
            SequenceManage sequenceManage=new SequenceManage(session);
            SeqField seqf=new SeqField();
            seqf.setTableName(stopTab);
            seqf.setTableId(stopTab);
            seqf.setIdField("STOP_ID");
            seqf.setPadding(12);
            sequenceManage.createSeq(seqf, true);
        }

        String idvalue=json.getString("STOP_ID");
        if(idvalue==null) {
//            DBPub.resetSql_Create(session,"EXE_CONDITION_STOP");
            idvalue=DBPub.getIdKeyStr(session,"EXE_CONDITION_STOP");
//            SequenceManage sequenceManage=new SequenceManage(session);
//            idvalue=sequenceManage.getNextNumByStr("EXE_CONDITION_STOP");
            JSONObject map=new JSONObject();
            map.putAll(json);
            map.put("STOP_ID", idvalue);
            map.put("CONDITION_ID", condition.getId());
            map.put("DIMENSION_ID", mid);
            map.put("STATE", "sent");
            map.put("CREATE_DATE", "SYSDATE");
            map.put("UPDATE_DATE", "SYSDATE");
            session.getForUpdate().insertTable("EXE_CONDITION_STOP", map);
        }
        JSONObject u=new JSONObject();
        u.put("STOP_ID", idvalue);
        session.getForUpdate().update(" DELETE "+stopTab+" WHERE STOP_ID=#{STOP_ID}", u);
        JSONArray list= JSON.toJSONArray(json.get("item"));
        int len=list.size();
        for(int i=0; i<len; i++){
            JSONObject m=list.get(i);
            JSONObject mx=new JSONObject();
            ArrayList<String> mlist=m.getKeylist();
            int jlen=mlist.size();
            for(int j=0; j<jlen; j++){
                String key=mlist.get(j);
                Object obj=m.get(key);
                if(obj instanceof Map){
                    JSONObject json1=JSON.toJSON(obj);
                    mx.put(key, json1.getString("ID"));
                } else {
                    mx.put(key, obj);
                }
            }
            mx.put("STATE", "sent");
            mx.put("STOP_ID", idvalue);
            mx.put("LAST_UPDATED_STAMP","SYSDATE");
            session.getForUpdate().insertTable(stopTab, mx);
        }
        return idvalue;
    }

    public void deleteStop(String mid, JSONObject json) throws Exception {
        String tabName = condition.getTableKey().getTabName(mid);
        String stopTab=tabName+"_EXEC_STOP";
        JSONObject param=new JSONObject();
        param.put("STOP_ID", json.get("STOP_ID"));
        param.put("LAST_UPDATED_STAMP_OLD", json.get("LAST_UPDATED_STAMP_OLD"));
        param.put("autoCompletion","0");
        String sql=" DELETE EXE_CONDITION_STOP WHERE STOP_ID=#{STOP_ID} AND TO_CHAR(LAST_UPDATED_STAMP, 'YYYYMMDD.HH24MISS')||'.000'=#{LAST_UPDATED_STAMP_OLD} ";
        if(session.getForUpdate().update(sql, param)==0){
            throw new Exception("当前数据已经改变，请重新操作！");
        };
        sql=" DELETE "+stopTab+" WHERE STOP_ID=#{STOP_ID} ";
        session.getForUpdate().update(sql, param);
    }

    public JSONObject queryStop(JSONObject input) throws Exception {
        String sql="SELECT * FROM EXE_CONDITION_STOP WHERE 1=1 ";
        final JSONObject[] result = {null};
        session.getForResultSet().sql(sql, input, new QueryCallBackHandler(){
            @Override
            public void getData(SqlResultSet rs, JSONArray rslist) throws Exception {
                if(rs.next()){
                    JSONObject json=rs.toRowJson();
                    String cid=json.getString("CONDITION_ID");
                    String mid=json.getString("DIMENSION_ID");
                    Condition con= ConditionUtil.getCondition(cid, session);
                    String tabName=con.getTableKey().getTabName(mid);
                    JSONObject inp=new JSONObject();
                    inp.put("STOP_ID", json.getString("STOP_ID"));
                    String sql=" SELECT * FROM "+tabName+"_EXEC_STOP A WHERE 1=1 ";
                    json.put("ITEM", session.getForJSON().query(sql, inp));
                    result[0] =json;
                }
            }
        });
        return result[0];
    }

    public void execStop(String mid, JSONObject input, String personId) throws Exception {
        ConSave conSave=new ConSave(condition);
        conSave.stopExec(mid, input, personId);
    }

}
